package com.up.api.thread;

import java.util.Collection;
import java.util.Objects;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: baiMl
 * @title: ThreadTaskQueue
 * @projectName: 海联技术中台V2.0
 * @depart 软件事业部
 * @description: 重写阻塞队列，重写线程池取任务
 * @date: 2023/9/21 10:03 (星期四)
 * @since V2.0
 */
public class ThreadTaskQueue extends LinkedBlockingQueue<Runnable> {
    private static final long serialVersionUID = -8714810933165064521L;

    private static final int DEFAULT_FORCED_REMAINING_CAPACITY = -1;

    private transient volatile ThreadPoolExecutor parent = null;

    private int forcedRemainingCapacity = -1;

    public ThreadTaskQueue() {
        super();
    }

    public ThreadTaskQueue(int capacity) {
        super(capacity);
    }

    public ThreadTaskQueue(Collection<? extends Runnable> c) {
        super(c);
    }

    public void setParent(ThreadPoolExecutor tp) {
        parent = tp;
    }

    public boolean force(Runnable o) {
        if (parent == null || parent.isShutdown())
            throw new RejectedExecutionException("thread executor is not run!");
        return super.offer(o); //forces the item onto the queue, to be used if the task is rejected
    }

    public boolean force(Runnable o, long timeout, TimeUnit unit) throws InterruptedException {
        if (parent == null || parent.isShutdown())
            throw new RejectedExecutionException("thread executor is not run!");
        return super.offer(o, timeout, unit); //forces the item onto the queue, to be used if the task is rejected
    }

    public ThreadPoolExecutor getExecutor() {
        return parent;
    }

    @Override
    public boolean offer(Runnable o) {
        //如果没有设置parent 线程池，则直接调用父类
        if (parent == null) {
            return super.offer(o);
        }
        //线程池的大小已经等于了最大线程，这个时候只需要进入队列排队即可
        if (parent.getPoolSize() == parent.getMaximumPoolSize()) {
            return super.offer(o);
        }
        //正在执行的线程小于线程池的大小，说明存在空闲线程(空闲线程需从队列取数据 getActiveCount+1)
        if (parent.getActiveCount() < (parent.getPoolSize())) {
            return super.offer(o);
        }
        //如果线程数少于最大线程数，则创建一个新线程（最大线程数优先于队列的做法）  2  400
        if (parent.getPoolSize() < parent.getMaximumPoolSize()) {
            //返回false就代表不入队，使用非核心线程数
            return false;
        }
        //如果以上条件都不满足，采用默认的做法就是直接进入队列等待调度
        return super.offer(o);
    }


//    @Override
//    public Runnable poll(long timeout, TimeUnit unit)
//            throws InterruptedException {
//        Runnable runnable = super.poll(timeout, unit);
//        if (runnable == null && parent != null) {
//            // the poll timed out, it gives an opportunity to stop the current
//            // thread if needed to avoid memory leaks.
//            parent.stopCurrentThreadIfNeeded();
//        }
//        return runnable;
//    }
//
//    @Override
//    public Runnable take() throws InterruptedException {
//        if (parent != null && parent.currentThreadShouldBeStopped()) {
//            return Objects.requireNonNull(poll(parent.getKeepAliveTime(TimeUnit.MILLISECONDS),
//                    TimeUnit.MILLISECONDS));
//            // yes, this may return null (in case of timeout) which normally
//            // does not occur with take()
//            // but the ThreadPoolExecutor implementation allows this
//        }
//        return super.take();
//    }
//
//    @Override
//    public int remainingCapacity() {
//        if (forcedRemainingCapacity > DEFAULT_FORCED_REMAINING_CAPACITY) {
//            // ThreadPoolExecutor.setCorePoolSize checks that
//            // remainingCapacity==0 to allow to interrupt idle threads
//            // I don't see why, but this hack allows to conform to this
//            // "requirement"
//            return forcedRemainingCapacity;
//        }
//        return super.remainingCapacity();
//    }
//
//    public void setForcedRemainingCapacity(int forcedRemainingCapacity) {
//        this.forcedRemainingCapacity = forcedRemainingCapacity;
//    }
//
//    public void resetForcedRemainingCapacity() {
//        this.forcedRemainingCapacity = DEFAULT_FORCED_REMAINING_CAPACITY;
//    }


}
